﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GiaoTrinhEPU.Repositories.Interfaces;
using GiaoTrinhEPU.Caching;


namespace GiaoTrinhEPU.Repositories.Repositories
{
    public class MenuRepository : BaseRepository, IMenuRepository
    {
        public MenuRepository() : base() { }
        public MenuRepository(ICacheProvider cacheProvider) : base(cacheProvider) { }

        /// <summary>
        /// Clear cache of all Applications
        /// </summary>
        public void ClearCache()
        {
            Cache.Invalidate("menus");
        }

        /// <summary>
        /// Clear cache of the Application
        /// </summary>
        /// <param name="key"></param>
        public void ClearCache(String key)
        {
            Cache.Invalidate("menu-" + key);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public IEnumerable<Menu> ListMenus(Core.Role role)
        {
            // First, check the cache
            IEnumerable<Menu> ListMenusData = Cache.Get("ListMenus") as IEnumerable<Menu>;

            // If it's not in the cache, we need to read it from the repository
            if (ListMenusData == null)
            {
                // Get the repository data
                try
                {
                    using (var db = new ThuVienEPUDataContext())
                    {
                        ListMenusData = db.Menus.Where(a => a.Role.Equals(role.ToString())).ToList();
                    }
                }
                catch (Exception ex)
                {
                    Logger.Writer.Write(ex.Message, ex.Source);
                }

                if (ListMenusData.Any())
                {
                    // Put this data into the cache for 60 minutes
                    Cache.Set("ListMenus", ListMenusData, GiaoTrinhEPU.Caching.Properties.Settings.Default.CacheTime);
                }
            }

            return ListMenusData;
        }
    }
}
